package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCategoryListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetCategoryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCategoryListLogic {
	return &GetCategoryListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetCategoryListLogic) GetCategoryList(in *Article.ArticleRequest) (*Article.GetCategoryListResponse, error) {
	var categoryVoList []models.CategoryVo
	models.Db.Model(new(models.Category)).Find(&categoryVoList)
	for i, v := range categoryVoList {
		var articleCount int64
		models.Db.Model(new(models.Article)).Where("category_id = ?", v.Id).Count(&articleCount)
		categoryVoList[i].ArticleCount = int(articleCount)
	}
	var categoryVoListResponse []*Article.CategoryVo
	copier.Copy(&categoryVoListResponse, &categoryVoList)
	for i, v := range categoryVoList {
		categoryVoListResponse[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
		categoryVoListResponse[i].UpdateTime = helper.MyTimeToTimestamp(v.UpdateTime)
	}
	return &Article.GetCategoryListResponse{
		Code:           int64(HttpCode.SUCCESS),
		CategoryVoList: categoryVoListResponse,
	}, nil
}
